<template>
  <!-- 空海派列表 -->
  <customContainer ref="mainRef" :config="mainConfig" />
  <div>
    <!-- 导入pod,订单详情 -->
    <el-dialog
      v-model="openPOD"
      :title="title"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="PODupload"
        class="upload-demo"
        drag
        multiple
        action="#"
        accept=".jpg,.pdf"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="false"
        :on-remove="handleRemove"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传jpg/pdf，且不超过30个文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="info" @click="openPOD = false">取消</el-button>
          <el-button type="primary" @click="uploadPODs">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 文件上传 -->
    <el-dialog
      v-model="openBulkImport"
      :title="title2"
      width="30%"
      :before-close="cancle3"
    >
      <el-upload
        ref="plUpload"
        class="upload-demo"
        accept=".xlsx,.xls"
        action="#"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="false"
        :on-remove="handleRemove"
        :on-change="handleFileChange"
        drag
        multiple
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">提示:仅允许导入"xls"或"xlsx"格式文件!</div>
          <el-link
            v-if="title2 =='导入订单'"
            type="info"
            style="font-size: 12px;color: red;"
            @click="importTemplate"
          >
            下载模板
          </el-link>
          <el-link
            v-if="title2 == '轨迹批量上传'"
            type="info"
            style="font-size: 12px;color: red;"
            @click="importTemplate2"
          >
            下载模板
          </el-link>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button typr="info" @click="cancle3">取消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="submitFileForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 批量修改价格 -->
    <el-dialog
      v-model="priceDialog"
      title="批量修改价格"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="priceRef"
        :model="editPriceForm"
        label-width="80px"
        :rules="pieceRules"
      >
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="editPriceForm.unitPrice" style="width: 175px;"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="priceDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePrice">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 详情页 -->
    <orderDetail ref="setFormRef" @refush="init" />
    <!-- 卡牌轨迹管理 -->
    <KBatchTrajectory ref="KPRef"></KBatchTrajectory>
    <feeName ref="feeRef"></feeName>
    <ysFeename ref="ysRef" title="应收费管理"></ysFeename>
    <!--打单-->
    
    <el-dialog
      v-model="open4"
      width="1200px"
      :title="title5"
      :fullscreen="false"
      :close-on-click-modal="false"
    >
      <div> 客户单号：{{ waybillNos }}</div>
      <upsPreparation ref="upsPlsyRef"></upsPreparation>
      <div>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="handlePreparationEnd">
              打单完成
            </el-button>

            <el-button @click="open4=false">关闭</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { ref, defineAsyncComponent, computed, getCurrentInstance } from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElDivider } from 'element-plus'
import { addDateRange } from '@/utils/index'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import userStore from '@/store/modules/user'
import {
  getlistOrder,
} from '@/api/order/orderInfo'
// eslint-disable-next-line max-len
import { uploadPOD, PlayBarCode, editPrice, pickingIsComplete, editOrderStatus, forcePlaceOrder, updateOrderStatus, kj, deleteInfo, importOrder, emsTrackUpdate, downLoadTag, getEmsOrderNO, selectPod, downloadInvoiceOrderFile } from '@/api/expressManager/orderList'

const user = userStore()
const dicts = useDicts()
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.客户)
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.货物类型)
dicts.setDicts(DictDirection.报价类型)
dicts.setDicts(DictDirection.收货站点)
dicts.setDicts(DictDirection.业务员)
dicts.setDicts(DictDirection.包裹状态)
dicts.setDicts(DictDirection.pod状态)
dicts.setDicts(DictDirection.费用名称)
dicts.setDicts(DictDirection.数据来源)
const openPOD = ref(false)
const fileList = ref([])
const title = ref(null)
const title2 = ref(null)
const openBulkImport = ref(false)
const priceDialog = ref(false)
const feeRef = ref(undefined)

const waybillNos = ref(null)
const btnLoading = ref(false)
const title5 = ref(null)
// 详情页
const orderDetail = defineAsyncComponent(() => import('./components/orderDetail.vue'))
const KBatchTrajectory = defineAsyncComponent(() => import('./components/KBatchTrajectory.vue'))
const feeName = defineAsyncComponent(() => import('./components/feeName.vue'))
const ysFeename = defineAsyncComponent(() => import('./components/ysFeename.vue'))
const upsPreparation = defineAsyncComponent(() => import('./components/upsPreparation.vue'))
const SelfDropdown = defineAsyncComponent(() => import('./components/SelfDropdown.vue'))
const
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  // loading加载
  // 文件上传
  PODupload = ref(null),
  plUpload = ref(null),
  // 导入文件
  // PODupload = ref(null),
  priceRef = ref(null),
  upsPlsyRef = ref(undefined),
  KPRef = ref(undefined),
  // KPOpen=ref(false),
  {
    appContext: {
      config: {
        globalProperties: { $download, $validateForm },
      },
    },
  } = getCurrentInstance()
const userIds = user.user.userId
const deptIds = user.user.deptId
const form = ref({
  pageSize: 10,
  pageNum: 1,
  clientId: undefined,
  orderNo: undefined,
  waybillNo: undefined,
  mainTransferOrderNo: undefined,
  transportType: 1,
  productType: undefined,
  customerCode: undefined,
  areaCode: undefined,
  receivingSite: undefined,
  marketProducts: undefined,
  goodsType: undefined,
  isPod: undefined,
  businessManager: undefined,
  consigneeCountry: undefined,
  consigneePostcode: undefined,
  splittingStatus: undefined,
  maker: undefined,
  tagNumber: undefined,
  dataSources: undefined,
  pickingStatus: undefined,
  zDdateRange: undefined,
  isFasteners: 1,
  dataSource: 1,
  uesrId: userIds,
  deptId: deptIds,
})
const mainRef = ref(null)
const query = ref({
  pageSize: 10,
  pageNum: 1,
  isFasteners: 1,
  uesrId: userIds,
  deptId: deptIds,
})
const dateRange = ref([])
const open4 = ref(false)
const pieceRules = {
  unitPrice: [{ required: true, message: '必填', trigger: 'blur' }],
}
// 表格格式化
const formatterRules = (row, column) => {
  console.log(row, column)
}
// 非多个禁用
const orderNoLists = ref([])
const selectSplittingStatus = ref([])
const currentPickingStatus = ref([])
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  console.log(rows)
  orderNoLists.value = rows.map((item) => item.orderNo)
  selectSplittingStatus.value = rows.map(el => el.splittingStatus)
  currentPickingStatus.value = rows.map(el => el.pickingStatus)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
// 操作
const typeProducts = ref([])
const getList = () => {
  const querys = query.value
  getlistOrder(querys).then(res => {
    console.log(res)
  })
}
// 修改
const handleUpdate = (row: { [key: string]: any }) => {
  console.log(setFormRef.value)
  
  setFormRef.value.openDetail = true
  setFormRef.value.idss = row.id
  setFormRef.value.title = '订单修改'
  setFormRef.value.orderNOs = row.orderNo
  setFormRef.value.disableds = false
  setFormRef.value.initData(row.id)
  setFormRef.value.xg = '1'
  typeProducts.value = row && row.typeProducts
}

// 详情
// const openDetail = ref(false)
const setFormRef = ref(undefined)
const rowId = ref([])
// 详情
const handleRouterPush = (row: { [key: string]: any }) => {
  setFormRef.value.openDetail = true
  setFormRef.value.title = '订单详情'
  setFormRef.value.idss = row.id
  setFormRef.value.disableds = true
  setFormRef.value.orderNOs = row.orderNo
  setFormRef.value.xg = '2'
  setFormRef.value.initData(row.id)
}

// 导出pod
const podHand = (row: { [key: string]: any }) => {
  rowId.value = row.id
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value))
  $download('order/order/info/exportPOD', { orderNoList }, `pod_${ new Date().getTime() }.zip`)
}

// 导入pod
const podAdd = () => {
  title.value = '导入pod'
  openPOD.value = true
  // proxy.$refs.uploadPOD && proxy.$refs.uploadPOD.clearFiles()
}
const { proxy } = getCurrentInstance() as any

// 上传

// 上传前校验
const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 10MB！')
    return
  }
  if (fileList.value.length > 30) {
    ElMessage.error('只支持上传三十个文件')
  }
}
const handleFileChange = (file, fileList) => {
  fileList.value = fileList
}
const handleRemove = (file, fileList) => {
  fileList.value = fileList
}
const uploadPODs = () => {
  const data = new FormData()
  proxy.fileList.forEach(el => {
    data.append('files', el.raw)
  })
  return uploadPOD(data).then(res => {
    if (res.code == 200) {
      openPOD.value = false
      ElMessage.success(res.msg)
      proxy.$refs.PODupload.clearFiles()
    }
  })
}
// 下载模板
const importTemplate = () => {
  $download('order/order/info/templateDownLoad/null', {}, `orderTemplate_${ new Date().getTime() }.xlsx`)
}
const importTemplate2 = () => {
  $download('order/ems/emsTrackUpdateDownLoad', {}, `emsTrackUpdateDownLoad${ new Date().getTime() }.xlsx`)
}
// const fileList1 = ref(undefined)
// 导入订单
const submitFileForm = () => {
  if (title2.value == '导入订单') {
    btnLoading.value = true
    const data = new FormData()
    proxy.fileList.forEach(el => {
      data.append('file', el.raw)
    })
    const deptId = form.value.deptId
    const ds = form.value.dataSource
    return importOrder(deptId, ds, data).then(res => {
      if (res.code == 200) {
        openPOD.value = false
        ElMessage.success(res.msg)
        mainRef.value.getList()
        proxy.$refs.PODupload.clearFiles()
        btnLoading.value = false
      } else {
        ElMessage.error(res.msg)
        btnLoading.value = false
      }
    }).catch(err => {
      console.log(err)
      btnLoading.value = false
    })
  }
  if (title2.value == '轨迹批量上传') {
    btnLoading.value = true
    const data = new FormData()
    proxy.fileList.forEach(el => {
      data.append('file', el.raw)
    })
   
    return emsTrackUpdate(data).then(res => {
      if (res.code == 200) {
        openPOD.value = false
        ElMessage.success(res.msg)
        mainRef.value.getList()
        proxy.$refs.PODupload.clearFiles()
        btnLoading.value = false
      } else {
        ElMessage.error(res.msg)
        btnLoading.value = false
      }
    }).catch(err => {
      console.log(err)
      btnLoading.value = false
    })
  }
}
const cancle3 = () => {
  openBulkImport.value = false
  proxy.$refs.plUpload.clearFiles()
}
// 导入订单
const handleImport = () => {
  openBulkImport.value = true
  title2.value = '导入订单'
}
// 导出提单数据
const handleExportDeliverMerge = () => {
  const data = query.value
  $download('order/deliveryMerge/exportDeliverMerge', data, `提单数据_${ new Date().getTime() }.xlsx`)
}
// 导出订单出货
const handleDeliverExport = () => {
  const data = query.value
  $download('order/order/info/exportCargoDetails', data, `订单出货_${ new Date().getTime() }.xlsx`)
}
// 打标签
const handlePrintLabel = () => {
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value)) 

  if (orderNoList.length > 5) {
    ElMessage.error('打标签最多只能选5个')
  } else {
    return PlayBarCode({ orderNoList }).then(res => {
      if (res.code == 200) {
        mainRef.value.getList()
        for (let i = 0; i < res.data.length; i++) {
          window.open(res.data[i], `${ i }jj`)
        }
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}
const handlePrintLabel2 = (row: { [key: string]: any }) => {
  const orderNoList = [JSON.parse(JSON.stringify(row.orderNo))]
  PlayBarCode({ orderNoList }).then(res => {
    if (res.code == 200) {
      mainRef.value.getList()
      for (let i = 0; i < res.data.length; i++) {
        window.open(res.data[i], `${ i }jj`)
      }
    }
  })
}
// 签入
const handleCheckIn = () => {
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  const orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  const data = {
    orderNoList: orderNos,
    deptId: form.value.deptId,
  }
  if (xg == 0) {
    ElMessageBox.confirm('确认签入？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      editOrderStatus(data).then(res => {
        if (res.code == 200) {
          ElMessage.success('签入成功')
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else {
    ElMessage.error('只有未签入的订单才能签入')
  }
}
// 打印面单
const DownLoadTag = () => {
  const zd = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  if (zd[0] != 2) {
    ElMessage.error('只有订单状态为制单,才可以打印面单')
  } else {
    const orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
    // typeof orderNos == 'string' && (orderNos = [orderNos])
    // const orderNos1 = orderNos.join(',')
    downLoadTag({ orderNoList: orderNos }).then(res => {
      if (res.code == 200) {
        for (let i = 0; i < res.data.urlList.length; i++) {
          const urlList = unescape(res.data.urlList[i])
          window.open(urlList, `${ i }a`)
        }
      }
    }).catch(err => {
      console.log(err)
    })
  }
}
const editPriceForm = ref({ unitPrice: undefined })
// 批量修改价格
const handlePrice = () => {
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  const orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  const unitPrice = editPriceForm.value.unitPrice
  console.log('s')
  if (xg == 0) {
    ElMessage.error('订单状态为未签入的不能修改单价')
  } else {
    $validateForm(priceRef.value, () => {
      editPrice({ orderNos, unitPrice }).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改单价成功!')
          priceDialog.value = false
          editPriceForm.value.unitPrice = ''
          getList()
        } else {
          return ElMessage.error('修改单价失败')
        }
      })
    })
  }
}
// 拣货完成
const onPicking = () => {
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value))
  const zt = JSON.parse(JSON.stringify(currentPickingStatus.value))
  console.log(zt)
  
  if (zt == 1) {
    ElMessage.error('已经拣货完成了，请勿重复操作')
    return
  }
  return ElMessageBox.confirm('确认拣货完成?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    pickingIsComplete({ orderNoList }).then(res => {
      if (res.code == 200) {
        mainRef.value.getList()
      }
    })
  })
  // ).catch(()=>{
  //   ElMessage.info('已取消拣货')
  // })
}
// 导出订单列表
const handleExport = () => {
  let data
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value))
  const deptId = query.value.deptId
  if (orderNoList.length !== 0) {
    let orderNos1 = JSON.parse(JSON.stringify(orderNoLists.value))
    typeof orderNos1 == 'string' && (orderNos1 = [orderNos1])
    const orderNo = orderNos1.join(',')
    data = addDateRange({ orderNo, deptId }, dateRange.value)
  } else {
    const queryParams = query.value
    data = addDateRange(queryParams, dateRange.value)
  }
  return $download('order/order/info/export', data, `orderList_${ new Date().getTime() }.xlsx`)
}
// 导出规格详情
const handleStandardExport = () => {
  const queryParams = query.value
  const data = addDateRange(queryParams, dateRange.value)
  let orderNos1 = JSON.parse(JSON.stringify(orderNoLists.value))
  typeof orderNos1 == 'string' && (orderNos1 = [orderNos1])
  const orderNo = orderNos1.join(',')
  data.orderNo = orderNo
  return $download('order/order/info/guigeExport', data, `规格详情导出_${ new Date().getTime() }.xlsx`)
}
// 导出运单详情
const ydHand = () => {
  const queryParams = query.value
  const data = addDateRange(queryParams, dateRange.value)
  let orderNos1 = JSON.parse(JSON.stringify(orderNoLists.value))
  typeof orderNos1 == 'string' && (orderNos1 = [orderNos1])
  const orderNo = orderNos1.join(',')
  data.orderNo = orderNo
  
  $download('order/order/info/exportDatails', data, `运单详情表_${ new Date().getTime() }.xlsx`)
}
// 导出库存
const handleExportInventory = () => {
  let data
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value))
  if (orderNoList.length !== 0) {
    let orderNos1 = JSON.parse(JSON.stringify(orderNoLists.value))
    typeof orderNos1 == 'string' && (orderNos1 = [orderNos1])
    const orderNo = orderNos1.join(',')
    data = addDateRange({ orderNo }, dateRange.value)
  } else {
    const queryParams = form.value
    data = addDateRange(queryParams, dateRange.value)
  }

  return $download('order/order/info/inLibraryOrder/export', data, `库存_${ new Date().getTime() }.xlsx`)
}
// 强制制单
const handleForcePlaceOrder = () => {
  let orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  typeof orderNos == 'string' && (orderNos = [orderNos])
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  if (xg == 1) {
    ElMessageBox.confirm('确认强制制单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      forcePlaceOrder(orderNos).then(res => {
        if (res.code == 200) {
          ElMessage.success('强制制单成功')
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else {
    ElMessageBox.alert('含有不是签入状态的订单，不能强制制单')
  }
}
// 退回制单
const handleSeniorUpdate = (row: { [key: string]: any }) => {
  // updateOrderStatus
  const orderNos = row.orderNo
  
  ElMessageBox.confirm('此操作将退回到制单状态, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    updateOrderStatus({ orderNo: orderNos }).then(res => {
      if (res.code == 200) {
        ElMessage.success('退回成功')
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
// 扣件
const handleFasteners = (row: { [key: string]: any }) => {
  const orderNos = row.orderNo
  ElMessageBox.confirm('敏感操作！是否继续？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    kj(orderNos).then(res => {
      if (res.code == 200) {
        ElMessage.success('扣件成功')
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
// 打印卡派面单
const handleKForcePlaceOrder = () => {
  let orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  typeof orderNos == 'string' && (orderNos = [orderNos])
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  if (xg != 1) {
    ElMessage.error('只有订单状态为签入,才可以打印面单')
  } else {
    ElMessageBox.confirm('确定打印卡派面单, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      getEmsOrderNO({ orderNoList: orderNos }).then(res => {
        if (res.code == 200) {
          mainRef.value.getList()
          res.data.forEach((el, index) => {
            window.open(el, `${ index }a`)
          })
        }
      }).catch(() => {
        ElMessage.info('已取消打印卡派面单')
      })
    })
  }
}
// 应收费
const handleManagementOfSurcharges = (row: { [key: string]: any }) => {
  feeRef.value.feeOpen = true
  feeRef.value.title = '应收费管理'
  feeRef.value.orderNoss = row.orderNo
  feeRef.value.getList(row.orderNo)
}

const handlePreparationEnd = () => {}
// 撤单
const retuenDel = (row: { [key: string]: any }) => {
  ElMessageBox.prompt('请输入备注', '提示', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputPattern: /\S/,
    inputErrorMessage: '备注不能为空',
  }).then(({ value }) => {
    const ids = row.id
    const remaraks = value
    const data = {
      remarks: remaraks,
      orderNo: row.orderNo,
    }
    console.log(data, ids)
    deleteInfo(ids, data).then(res => {
      if (res.code == 200) {
        ElMessage.success('撤单成功')
        mainRef.value.getList()
        init()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 打单
const playUps = (row: { [key: string]: any }) => {
  open4.value = true
  title5.value = '打单'
  upsPlsyRef.value.orderNoss = row.orderNo
  upsPlsyRef.value.initList()
}
// 打单详情
const handleUps = (row: { [key: string]: any }) => {
  title5.value = '打单详情'
  open4.value = true
  upsPlsyRef.value.orderNoss = row.orderNo
  upsPlsyRef.value.initList()
}
// 查看pod
const handleUploadPOD = (row: { [key: string]: any }) => {
  const orderNos = row.orderNo
  const data = {
    orderNo: orderNos,
  }
  selectPod(data).then(res => {
    if (res.code == 200) {
      if (!res.data.length) return ElMessage.error('POD列表为空')
      res.data[0].returnPOdList.forEach(el => {
        const url = unescape(el)
        window.open(url)
      })
    }
  })
}
// 下载发票
const handleUploadInvoices = (row: { [key: string]: any }) => {
  const data = {
    orderNo: row.orderNo,
  }
  downloadInvoiceOrderFile(data).then(res => { 
    if (res.code == 200) {
      const link = document.createElement('a')
      link.download = `订单发票_${ new Date().getTime() }.xlsx`
      link.style.display = 'none'
      link.href = res.data[0].fileUrl
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  })
  // return $download('order/order/info/downloadInvoiceOrderFile', { orderNo: s }, `订单发票_${ new Date().getTime() }.xlsx`)
}

// 卡派轨迹管理
const handleKBatchTrajectory = () => {
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value))
  console.log(orderNoList)
  
  KPRef.value.KPOpen = true
  KPRef.value.selfOrderNos = orderNoList[0]
  KPRef.value.getList(orderNoList[0].value)
}
const handleKPUpload = () => {
  openBulkImport.value = true
  title2.value = '轨迹批量上传'
}

// const handleFileExceed = () => {
//   ElMessage.error('超出限定文件数量！')
// }

const init = () => {
  form.value.pageNum = 1
  mainRef.value.getList()
}
const mainConfig = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '系统订单号',
            prop: 'orderNo',
            option: {
              placeholder: '请输入系统订单号',
              type: 'textarea',
            },
          },
          {
            label: '客户单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入客户单号',
              type: 'textarea',
            },
          },
          {
            label: '主转单号',
            prop: 'mainTransferOrderNo',
            option: {
              placeholder: '请输入主转单号',
              type: 'textarea',
            },
          },
          {
            type: 'select',
            label: '运输类型',
            prop: 'transportType',
            option: {
              dictInfo: { dict: DictDirection.运输类型 },
            },
          },
          {
            type: 'select',
            label: '产品类别',
            prop: 'productType',
            option: {
              dictInfo: { dict: DictDirection.产品类别 },
            },
          },
          {
            type: 'select',
            label: '客户名称',
            prop: 'customerCode',
            option: {
              dictInfo: { dict: DictDirection.客户 },
            },
          },
          {
            type: 'select',
            label: '所属站点',
            prop: 'areaCode',
            option: {
              dictInfo: { dict: DictDirection.收货站点 },
            },
          },
          {
            type: 'select',
            label: '拣货站点',
            prop: 'receivingSite',
            option: {
              dictInfo: { dict: DictDirection.收货站点 },
            },
          },
          {
            type: 'select',
            label: '销售产品',
            prop: 'marketProducts',
            option: {
              dictInfo: { dict: DictDirection.产品 },
            },
          },
          {
            type: 'select',
            label: '收货类型',
            prop: 'goodsType',
            option: {
              dictInfo: { dict: DictDirection.货物类型 },
            },
          },
          {
            type: 'select',
            label: 'POD状态',
            prop: 'isPod',
            option: {
              dictInfo: { dict: DictDirection.是否禁用字典 },
            },
          },
          {
            type: 'select',
            label: '业务员',
            prop: 'businessManager',
            option: {
              dictInfo: { dict: DictDirection.业务员 },
            },
          },
          {
            type: 'selectv2',
            label: '目的国家',
            prop: 'consigneeCountry',
            option: {
              dictInfo: { dict: DictDirection.国家 },
            },
          },
          {
            label: '邮编',
            prop: 'consigneePostcode',
            option: {
              controls: false,
              // directives: [['hasPermi', ['number'], 'arg']],
            },
          },

          {
            type: 'datePicker',
            label: '创建日期',
            prop: 'daterange',

            option: {
              type: 'daterange',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            type: 'select',
            label: '包裹状态',
            prop: 'splittingStatus',
            option: {
              dictInfo: { dict: DictDirection.包裹状态 },
            },
          },
          {
            type: 'date-picker',
            label: '制单日期',
            prop: 'zDdateRange',
            option: {
              type: 'daterange',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            label: '标签号',
            prop: 'tagNumber',
          },
          {
            type: 'select',
            label: '数据来源',
            prop: 'dataSources',
            option: {
              dictInfo: { dict: DictDirection.数据来源 },
            },
          },
          {
            type: 'select',
            label: '拣货状态',
            prop: 'pickingStatus',
            option: {
              dictInfo: { dict: DictDirection.拣货状态 },
            },
          },
          {
            type: 'select',
            label: '扣件状态',
            prop: 'isFasteners',
            option: {
              dictInfo: { dict: DictDirection.扣件状态 },
            },
          },
        ],
        queryParams: form.value,

      },
      btns: [
        {
          title: '导出POD',
          type: 'primary',
          disabled: multiple.value,
          onClick: podHand,
         
        },
        {
          title: '上传POD',
          type: 'primary',
          onClick: podAdd,
           
        },
        {
          title: '导出运单详情',
          type: 'primary',
          disabled: multiple.value,
          onClick: ydHand,
          
        },
        {
          title: '导出提单数据',
          type: 'info',
          onClick: handleExportDeliverMerge,
         
        },
        {
          title: '导入订单',
          type: 'info',
          onClick: handleImport,
         
        },
        {
          title: '导出订单出货',
          type: 'info',
          onClick: handleDeliverExport,
        
        },
        {
          title: '导出订单列表',
          type: 'warning',
          onClick: handleExport,
         
        },
        {
          title: '打标签',
          type: 'success',
          disabled: multiple.value,
          onClick: handlePrintLabel,
         
        },
        {
          title: '打印面单',
          type: 'danger',
          disabled: multiple.value,
          onClick: DownLoadTag,
         
        },

        {
          title: '签入',
          type: 'success',
          disabled: multiple.value,
          onClick: handleCheckIn,

        },
        {
          title: '强制制单',
          type: 'danger',
          disabled: multiple.value,
          onClick: handleForcePlaceOrder,
          
        },

        {
          title: '卡派轨迹管理',
          type: 'primary',
          disabled: multiple.value,
          onClick: handleKBatchTrajectory,
         
        },

        {
          title: '打印卡派面单',
          type: 'success',
          disabled: multiple.value,
          onClick: handleKForcePlaceOrder,
         
        },

        {
          title: '导出规格详情',
          type: 'primary',
          disabled: multiple.value,
          onClick: handleStandardExport,
          
        },

        {
          title: '轨迹批量上传',
          type: 'primary',
          onClick: handleKPUpload,
          
        },
        {
          title: '导出库存',
          type: 'info',
          onClick: handleExportInventory,
          
        },
        {
          title: '批量修改价格',
          disabled: multiple.value,
          
          onClick() {
            priceDialog.value = true
          },
        },
        {
          title: '拣货完成',
          type: 'primary',
          disabled: multiple.value,
          onClick: onPicking,
          
        },
      ],
      table: {
        formatter: formatterRules,
        columns: [
          { type: 'selection', width: '55' },
          {
            label: '创建日期',
            prop: 'orderTime',
            width: '150',
            align: 'center',
           
          },
          { label: '客户单号', prop: 'waybillNo', width: '150', align: 'center' },
          { label: '主转单号', prop: 'mainTransferOrderNo', width: '150', align: 'center' },
          { label: '客户名称', prop: 'customerName', width: '120', align: 'center' },
          {
            label: '销售产品',
            prop: 'marketProducts',
            width: '100',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.产品,
              rowKey: 'marketProducts',
            },
          },
          { label: '总实重', prop: 'receivingTotalWeight', align: 'center' },
          { label: '件数', prop: 'receivingTotal', align: 'center' },
          { label: '拣货状态',
            prop: 'pickingStatus',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.拣货状态,
              rowKey: 'pickingStatus',
            },
          },
          { label: '所属站点',
            prop: 'areaCode',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.收货站点,
              rowKey: 'areaCode',
            },
          },
          { label: '拣货站点',
            prop: 'site',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.收货站点,
              rowKey: 'site',
            } },
          { label: '邮编', prop: 'consigneePostcode', align: 'center' },
          { label: '国家',
            prop: 'consigneeCountry',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.国家,
              rowKey: 'consigneeCountry',
            } },
          { label: '打印标签次数', prop: 'printTagCount', align: 'center' },
          { label: '标签号', prop: 'tagNumber', align: 'center' },
          { label: '货物类型',
            prop: 'goodsType',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.包裹类型,
              rowKey: 'goodsType',
            },
          },
          { label: '业务员', prop: 'businessManager', align: 'center' },
          { label: '制单人', prop: 'maker', align: 'center' },
          { label: '制单日期', prop: 'makerDate', align: 'center', width: '120' },
          { label: '报关件', prop: 'customsDeclaration', align: 'center' },
          { label: '备注', prop: 'remarks', align: 'center', width: '80' },
          { label: '系统订单号', prop: 'orderNo', align: 'center', width: '150' },
          { label: 'POD',
            prop: 'isPod',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.pod状态,
              rowKey: 'isPod',
            },
          },
          { label: '数据来源',
            prop: 'dataSources',
            align: 'center',
            width: '120',
            autoFormatter: {
              dict: DictDirection.数据来源,
              rowKey: 'dataSources',
            } },
          {
            label: '操作',
            align: 'center',
            width: '252',
            fixed: 'right',
            render(h, params) {
              const seaBtn = [
                {
                  label: '退回制单',
                  clickFun: handleSeniorUpdate,
                  disabled: !(params.row.splittingStatus == 2 || params.row.splittingStatus == 4 || params.row.splittingStatus == 3),
                },
                {
                  label: '扣件',
                  clickFun: handleFasteners,
                  disabled: params.row.splittingStatus <= 0 || params.row.splittingStatus == 7,
                },
                {
                  label: '应收费',
                  clickFun: handleManagementOfSurcharges,
                  disabled: params.row.splittingStatus == 0,
                },
                
                {
                  label: '打单详情',
                  clickFun: handleUps,
                  disabled: params.row.splittingStatus < 1,
                },
                {
                  label: '撤单',
                  clickFun: retuenDel,
                  disabled: params.row.splittingStatus == -1 || params.row.status === '待核销',
                },
                {
                  label: '打单',
                  clickFun: playUps,
                  disabled: params.row.splittingStatus == 0 || params.row.splittingStatus == 14 || params.row.splittingStatus == 7,
                },
                {
                  label: '打标签',
                  clickFun: handlePrintLabel2,
                  disabled: params.row.splittingStatus == -1,
                },
                {
                  label: '查看pod',
                  clickFun: handleUploadPOD,
                  disabled: !params.row.isPod,
                },
                {
                  label: '下载发票',
                  clickFun: handleUploadInvoices,
                },       
              ]
              return [
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => { handleUpdate(params.row) },
                    disabled: params.row.splittingStatus != 0 && params.row.splittingStatus != 1,
                  },
                  {
                    default: () => '修改',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    // icon: el.icon,
                    onClick: () => { handleRouterPush(params.row) },
                  },
                  {
                    default: () => '详情',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  SelfDropdown,
                  {
                    items: [
                      ...seaBtn,
                    ],
                    onHandleCommand(command) {
                      command.clickFun && command.clickFun(params.row)
                    },
                  },
                ),
              ]
            },
          },
        ],

        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: getlistOrder,
      customKey: 'express/mainBusiness/oceanShipping/orderinfo',
    }
  },
  set(val) {
    return val
  },
})
</script>
<style lang="less" scoped>
/deep/.is-guttered {
  padding: 5px;
}
/deep/.el-button {
  padding: 5px 10px;
}
</style>
